import {dialog, ipcMain, webContents} from "electron"
import {events} from "@/ts.d/native/events";
import {CallBackStatus, download} from "@/native/utils/download";


// 下载事件  {url: string; fileName: string; file: {percent: number}}
ipcMain.handle(events.DOWNLOAD, (event, args: {url: string; fileName: string; /*文件标识*/fileSign?: string| any}) => {
  return new Promise((resolve, reject) => {
    download(args.url, args.fileName, (status, data) => {
      if(status===CallBackStatus.finish){
        resolve()
      }
      if(status===CallBackStatus.progress){
        webContents.getAllWebContents().forEach(window => {
          window.send(events.UPDATE_FILE_PERCENT, {fileSign : args.fileSign, data})
        })
      }
      if(status===CallBackStatus.error){
        reject(data.msg)
      }
    })
  })
})

// 选择目录
ipcMain.handle(events.SELECT_DIR, (event, args: any) => {
  return new Promise((resolve, reject) => {
    dialog.showOpenDialog({
      title: "请选择目录",
      defaultPath: args.path,
      properties: ["openDirectory"]
    }).then(value => {
      resolve(value)
    })
  })
})
